package com.yuwei.goods_detail

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Paint
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.GsonUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.tencent.mmkv.MMKV
import com.umeng.socialize.ShareAction
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import com.youth.banner.config.IndicatorConfig
import com.yuwei.base.RoutePath
import com.yuwei.goods_detail.adapter.BannerImageAdapter
import com.yuwei.common.mvi.BaseMviActivity
import com.yuwei.common.mvi.UiState
import com.yuwei.database.entity.GoodsEntityItem
import com.yuwei.database.entity.OrderEntity
import com.yuwei.goods_detail.adapter.AttrAdapter
import com.yuwei.goods_detail.adapter.CommentAdapter
import com.yuwei.goods_detail.databinding.ActivityGoodsDetailBinding
import com.yuwei.goods_detail.entity.*
import com.yuwei.image.glide.GlideImageLoader

/**
 *游戏鸿蒙-i视频-05-商品详情V1.1-20260612-崔志彪
 */
@Route(path = RoutePath.LIVE_GOODS_DETAIL_ACTIVITY)
class GoodsDetailActivity : BaseMviActivity<ActivityGoodsDetailBinding,GoodsDetailViewModel>() {
    private var banner2List = arrayListOf<BannerEntity>()
    private var commentAdapter = CommentAdapter()
    private var alpar = 0
    @Autowired(name = "goods_detail")
    lateinit var goodsEntityItem: GoodsEntityItem
    private val versionAdapter = AttrAdapter()
    private val colorAdapter = AttrAdapter()
    private val attrAdapter = AttrAdapter()
    override fun successData(it: UiState.onSuccess<*>) {
        when(it.type){
            "insertGoods" -> {
                ToastUtils.showShort("添加成功")
            }
            "addCar" -> {
                ToastUtils.showShort("添加成功")
            }
        }
    }

    override fun failureData(error: String) {

    }

    @SuppressLint("SuspiciousIndentation")
    override fun initView() {
        ARouter.getInstance().inject(this)
        vm.sendIntent(GoodsDetailIntent.insertGoods(goodsEntityItem))
        binding.goodsDetailBack.setOnClickListener {
            finish()
        }
        binding.goodsDetailMoney.text = "￥${goodsEntityItem.goods_default_price}"
        binding.goodsDetailMoney2.text = "￥${goodsEntityItem.goods_default_price+200}"
       binding.goodsDetailMoney2.paintFlags = binding.goodsDetailMoney2.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        Glide.with(this).load(goodsEntityItem.goods_detail_one).into(binding.goodsDetailImg1)
        Glide.with(this).load(goodsEntityItem.goods_detail_two).into(binding.goodsDetailImg2)
        val tag = "小店"
        val spannable = SpannableStringBuilder()
        // 创建自定义 Span（红色背景，白色文字，12dp圆角，8dp左右边距，4dp上下边距）
        val density = resources.displayMetrics.density
        val tagSpan = RoundedTagSpan(
            backgroundColor = Color.parseColor("#F13939"),
            textColor = Color.WHITE,
            cornerRadius = 3f * density, // 12dp 圆角
            horizontalPadding = (6 * density).toInt(), // 8dp 左右边距
            verticalPadding = (3 * density).toInt() // 4dp 上下边距
        )

        spannable.append(tag)
        spannable.setSpan(tagSpan, 0,tag.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannable.setSpan(ForegroundColorSpan(Color.parseColor("#FFFFFFFF")), 0, tag.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //拼接剩余文本
        spannable.append("  ${goodsEntityItem.goods_desc}") // 加空格分隔标签和内容
        //设置到 TextView
        binding.goodsDetailContent.text = spannable
        //banner2
        goodsEntityItem.bannerList.forEach {
           banner2List.add(BannerEntity(0,it))
        }

        binding.goodsDetailTopIv.run {
            addBannerLifecycleObserver(this@GoodsDetailActivity)
            setAdapter(BannerImageAdapter(banner2List))
            setIndicator(NumberIndicator(this@GoodsDetailActivity),true)
            setIndicatorGravity(IndicatorConfig.Direction.RIGHT)
        }



        binding.nestedScrollView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            alpar += scrollY - oldScrollY
            val a: Float = alpar / 500f
            binding.goodsDetailBg.alpha = a

        }
        //分享
        binding.goodsDetailShape.setOnClickListener {
            val web = UMWeb("https://detail.tmall.com/item.htm?id=916014416227&ns=1&priceTId=2147800517491270647358422e10af&spm=a21n57.sem.item.4.6bf83903pxWFFp&utparam=%7B%22aplus_abtest%22%3A%223b1d9f6db645d5ae7646cdb2a4a1e8e1%22%7D&xxc=ad_ztc")
            web.title =goodsEntityItem.goods_desc //标题
            web.setThumb(UMImage(this,goodsEntityItem.goods_default_icon)) //缩略图
            web.description = goodsEntityItem.goods_desc //描述
            ShareAction(this)
                .withMedia(web)
                .open()
        }
        // 访问列表
        //立即购买
        binding.goodsDetailPurchase.setOnClickListener {
            val popup = XPopup.Builder(this)
                .enableDrag(true)
                .asCustom(object : BottomPopupView(this) {
                    override fun getImplLayoutId(): Int {
                        return R.layout.goods_detail_standard
                    }
                    override fun onCreate() {
                        super.onCreate()
                        val goodsStandardBack = findViewById<ImageView>(R.id.goods_standard_back)
                        val goodsStandardIv = findViewById<ImageView>(R.id.goods_standard_iv)
                        val goodsStandardMoney = findViewById<TextView>(R.id.goods_standard_money)
                        val goodsStandardStock = findViewById<TextView>(R.id.goods_standard_stock)
                        val versionSelect = findViewById<TextView>(R.id.goods_version_select)
                        val attrSelect = findViewById<TextView>(R.id.goods_attr_select)
                        val colorSelect = findViewById<TextView>(R.id.goods_color_select)
                        val goodsStandardTypeTT = findViewById<TextView>(R.id.goods_detail_type_tt)
                        val goodsStandardTypeRV = findViewById<RecyclerView>(R.id.goods_detail_type)
                        val goodsStandardColorTT =
                            findViewById<TextView>(R.id.goods_detail_color_tt)
                        val goodsStandardColorRV =
                            findViewById<RecyclerView>(R.id.goods_detail_color)
                        val goodsStandardCollocateTT =
                            findViewById<TextView>(R.id.goods_detail_collocate_tt)
                        val goodsStandardCollocateRV =
                            findViewById<RecyclerView>(R.id.goods_detail_collocate)
                        val goodsStandardSubtractBtn =
                            findViewById<TextView>(R.id.goods_standard_btn_subtract)
                        val goodsStandardNum = findViewById<TextView>(R.id.goods_standard_num)
                        val goodsStandardAddBtn =
                            findViewById<TextView>(R.id.goods_standard_btn_add)
                        val goodsStandardBtn = findViewById<Button>(R.id.goods_standard_btn)
                        //返回
                        goodsStandardBack.setOnClickListener {
                            dismiss()
                        }
                        goodsStandardBtn.setOnClickListener {
                            if((attrSelect.visibility == View.VISIBLE&&attrSelect.text.toString().isEmpty())||(colorSelect.visibility == View.VISIBLE&&colorSelect.text.toString().isEmpty())||(versionSelect.visibility == View.VISIBLE&&versionSelect.text.toString().isEmpty())){
                                ToastUtils.showShort("请选择商品规格")
                                return@setOnClickListener
                            }
                            finish()
                            vm.sendIntent(GoodsDetailIntent.insertOrder(OrderEntity(
                                id = 0,
                                count = goodsStandardNum.text.toString().toInt(),
                                goods_default_icon = goodsEntityItem.goods_default_icon,
                                goods_default_price = goodsEntityItem.goods_default_price,
                                goods_desc = goodsEntityItem.goods_desc,
                                goods_id = goodsEntityItem.id,
                                user_id = MMKV.defaultMMKV().decodeInt("userId",0),
                                0
                            )))
                            ARouter.getInstance().build(RoutePath.MODULE_ORDER_CONFIRM_ORDER_ACTIVITY).navigation()
                        }
                        //数量加减
                        goodsStandardSubtractBtn.setOnClickListener {
                            if (goodsStandardNum.text.toString().toInt() == 1) {
                                ToastUtils.showShort("不能再减了")
                                return@setOnClickListener
                            }
                            goodsStandardNum.text =
                                (goodsStandardNum.text.toString().toInt() - 1).toString()
                        }
                        goodsStandardAddBtn.setOnClickListener {
                            if(goodsStandardNum.text.toString().toInt() >= goodsEntityItem.goods_stock_count){
                                ToastUtils.showShort("库存不足")
                                return@setOnClickListener
                            }
                            goodsStandardNum.text =
                                (goodsStandardNum.text.toString().toInt() + 1).toString()
                        }

                        //图片
                        GlideImageLoader.loadImage(this@GoodsDetailActivity,goodsStandardIv,goodsEntityItem.goods_default_icon)
                        //money
                        goodsStandardMoney.text = "￥${goodsEntityItem.goods_default_price}"
                        //库存
                        goodsStandardStock.text = "库存 ${goodsEntityItem.goods_stock_count} 件"
                        val productSpecs = GsonUtils.fromJson(
                            goodsEntityItem.goods_attribute,
                            ProductSpecs::class.java
                        )
                        // 保存基础价格
                        val basePrice = goodsEntityItem.goods_default_price
                        // 保存当前选中的规格和对应的加价
                        val selectedOptions = mutableMapOf(
                            "版本" to 0,
                            "配置" to 0,
                            "颜色" to 0
                        )

                        // 更新总价格的函数
                        fun updateTotalPrice() {
                            val totalExtra = selectedOptions.values.sum()
                            goodsEntityItem.goods_default_price = basePrice + totalExtra
                            goodsStandardMoney.text = "￥${goodsEntityItem.goods_default_price}"
                        }

                        // 版本规格
                        if (goodsEntityItem.goods_attribute.contains("版本")) {
                            versionSelect.visibility = View.VISIBLE
                            goodsStandardTypeTT.run {
                                text = "版本"
                                visibility = View.VISIBLE
                            }
                            versionAdapter.run {
                                setPosition(-1)
                                notifyDataSetChanged()
                                data.clear()
                                data.addAll(productSpecs.版本)
                                notifyDataSetChanged()
                                setOnItemClickListener { _, _, position ->
                                    versionSelect.text =  "${data[position]},"
                                    selectedOptions["版本"] = when(position) {
                                        1 -> 100
                                        2 -> 200
                                        3 -> 300
                                        4 -> 400
                                        else -> 0
                                    }
                                    setPosition(position)
                                    notifyDataSetChanged()
                                    updateTotalPrice()
                                }
                            }
                            goodsStandardTypeRV.run {
                                adapter = versionAdapter
                                layoutManager = LinearLayoutManager(this@GoodsDetailActivity, LinearLayoutManager.HORIZONTAL, false)
                            }
                        }

                        // 配置规格
                        if (goodsEntityItem.goods_attribute.contains("配置")) {
                            attrSelect.visibility = View.VISIBLE
                            goodsStandardCollocateTT.run {
                                text = "配置"
                                visibility = View.VISIBLE
                            }
                            attrAdapter.run {
                                setPosition(-1)
                                notifyDataSetChanged()
                                data.clear()
                                data.addAll(productSpecs.配置)
                                notifyDataSetChanged()

                                setOnItemClickListener { _, _, position ->
                                    attrSelect.text = "${data[position]}"
                                    selectedOptions["配置"] = when(position) {
                                        1 -> 100
                                        2 -> 200
                                        3 -> 300
                                        4 -> 400
                                        else -> 0
                                    }
                                    setPosition(position)
                                    notifyDataSetChanged()
                                    updateTotalPrice()
                                }
                            }
                            goodsStandardCollocateRV.run {
                                adapter = attrAdapter
                                layoutManager = LinearLayoutManager(this@GoodsDetailActivity, LinearLayoutManager.HORIZONTAL, false)
                            }
                        }
                        // 颜色规格
                        if (goodsEntityItem.goods_attribute.contains("颜色")) {
                            colorSelect.visibility = View.VISIBLE
                            goodsStandardColorTT.run {
                                text = "颜色"
                                visibility = View.VISIBLE
                            }

                            colorAdapter.run {
                                setPosition(-1)
                                notifyDataSetChanged()
                                data.clear()
                                data.addAll(productSpecs.颜色)
                                notifyDataSetChanged()
                                setOnItemClickListener { _, _, position ->
                                    colorSelect.text =data[position]
                                    selectedOptions["颜色"] = when(position) {
                                        1 -> 100
                                        2 -> 200
                                        3 -> 300
                                        4 -> 400
                                        else -> 0
                                    }
                                    setPosition(position)
                                    notifyDataSetChanged()
                                    updateTotalPrice()
                                }
                            }
                            goodsStandardColorRV.run {
                                adapter = colorAdapter
                                layoutManager = LinearLayoutManager(this@GoodsDetailActivity, LinearLayoutManager.HORIZONTAL, false)
                            }
                        }
                    }

                    override fun onDismiss() {
                        super.onDismiss()

                    }
                })
                popup.show()
        }
        binding.goodsDetailShopping.setOnClickListener {
            ARouter.getInstance().build(RoutePath.GOODS_SHOPPING).navigation()
        }
        binding.goddsDetailShoppingCar.setOnClickListener {
            val popup = XPopup.Builder(this)
                .enableDrag(true)
                .asCustom(object : BottomPopupView(this) {
                    override fun getImplLayoutId(): Int {
                        return R.layout.goods_detail_standard
                    }
                    override fun onCreate() {
                        super.onCreate()
                        val goodsStandardBack = findViewById<ImageView>(R.id.goods_standard_back)
                        val goodsStandardIv = findViewById<ImageView>(R.id.goods_standard_iv)
                        val goodsStandardMoney = findViewById<TextView>(R.id.goods_standard_money)
                        val goodsStandardStock = findViewById<TextView>(R.id.goods_standard_stock)
                        val versionSelect = findViewById<TextView>(R.id.goods_version_select)
                        val attrSelect = findViewById<TextView>(R.id.goods_attr_select)
                        val colorSelect = findViewById<TextView>(R.id.goods_color_select)
                        val goodsStandardTypeTT = findViewById<TextView>(R.id.goods_detail_type_tt)
                        val goodsStandardTypeRV = findViewById<RecyclerView>(R.id.goods_detail_type)
                        val goodsStandardColorTT =
                            findViewById<TextView>(R.id.goods_detail_color_tt)
                        val goodsStandardColorRV =
                            findViewById<RecyclerView>(R.id.goods_detail_color)
                        val goodsStandardCollocateTT =
                            findViewById<TextView>(R.id.goods_detail_collocate_tt)
                        val goodsStandardCollocateRV =
                            findViewById<RecyclerView>(R.id.goods_detail_collocate)
                        val goodsStandardSubtractBtn =
                            findViewById<TextView>(R.id.goods_standard_btn_subtract)
                        val goodsStandardNum = findViewById<TextView>(R.id.goods_standard_num)
                        val goodsStandardAddBtn =
                            findViewById<TextView>(R.id.goods_standard_btn_add)
                        val goodsStandardBtn = findViewById<Button>(R.id.goods_standard_btn)
                        //返回
                        goodsStandardBack.setOnClickListener {
                            dismiss()
                        }
                        goodsStandardBtn.setOnClickListener {
                            if((attrSelect.visibility == View.VISIBLE&&attrSelect.text.toString().isEmpty())||(colorSelect.visibility == View.VISIBLE&&colorSelect.text.toString().isEmpty())||(versionSelect.visibility == View.VISIBLE&&versionSelect.text.toString().isEmpty())){
                                ToastUtils.showShort("请选择商品规格")
                                return@setOnClickListener
                            }
                            dismiss()
                            vm.sendIntent(GoodsDetailIntent.goodsAddCar(GoodsCarBody(goodsStandardNum.text.toString().toInt(),goodsEntityItem.id)))

//                            ARouter.getInstance().build(RoutePath.MODULE_ORDER_CONFIRM_ORDER_ACTIVITY)
//                                .withSerializable("goods",goodsEntityItem)
//                                .withInt("count",goodsStandardNum.text.toString().toInt())
//                                .navigation()
                        }
                        //数量加减
                        goodsStandardSubtractBtn.setOnClickListener {
                            if (goodsStandardNum.text.toString().toInt() == 1) {
                                ToastUtils.showShort("不能再减了")
                                return@setOnClickListener
                            }
                            goodsStandardNum.text =
                                (goodsStandardNum.text.toString().toInt() - 1).toString()
                        }
                        goodsStandardAddBtn.setOnClickListener {
                            if(goodsStandardNum.text.toString().toInt() >= goodsEntityItem.goods_stock_count){
                                ToastUtils.showShort("库存不足")
                                return@setOnClickListener
                            }
                            goodsStandardNum.text =
                                (goodsStandardNum.text.toString().toInt() + 1).toString()
                        }

                        //图片
                        GlideImageLoader.loadImage(this@GoodsDetailActivity,goodsStandardIv,goodsEntityItem.goods_default_icon)
                        //money
                        goodsStandardMoney.text = "￥${goodsEntityItem.goods_default_price}"
                        //库存
                        goodsStandardStock.text = "库存 ${goodsEntityItem.goods_stock_count} 件"
                        val productSpecs = GsonUtils.fromJson(
                            goodsEntityItem.goods_attribute,
                            ProductSpecs::class.java
                        )
                        // 保存基础价格
                        val basePrice = goodsEntityItem.goods_default_price
                        // 保存当前选中的规格和对应的加价
                        val selectedOptions = mutableMapOf(
                            "版本" to 0,
                            "配置" to 0,
                            "颜色" to 0
                        )

                        // 更新总价格的函数
                        fun updateTotalPrice() {
                            val totalExtra = selectedOptions.values.sum()
                            goodsEntityItem.goods_default_price = basePrice + totalExtra
                            goodsStandardMoney.text = "￥${goodsEntityItem.goods_default_price}"
                        }

                        // 版本规格
                        if (goodsEntityItem.goods_attribute.contains("版本")) {
                            versionSelect.visibility = View.VISIBLE
                            goodsStandardTypeTT.run {
                                text = "版本"
                                visibility = View.VISIBLE
                            }
                            versionAdapter.run {
                                setPosition(-1)
                                notifyDataSetChanged()
                                data.clear()
                                data.addAll(productSpecs.版本)
                                notifyDataSetChanged()
                                setOnItemClickListener { _, _, position ->
                                    versionSelect.text =  "${data[position]},"
                                    selectedOptions["版本"] = when(position) {
                                        1 -> 100
                                        2 -> 200
                                        3 -> 300
                                        4 -> 400
                                        else -> 0
                                    }
                                    setPosition(position)
                                    notifyDataSetChanged()
                                    updateTotalPrice()
                                }
                            }
                            goodsStandardTypeRV.run {
                                adapter = versionAdapter
                                layoutManager = LinearLayoutManager(this@GoodsDetailActivity, LinearLayoutManager.HORIZONTAL, false)
                            }
                        }

                        // 配置规格
                        if (goodsEntityItem.goods_attribute.contains("配置")) {
                            attrSelect.visibility = View.VISIBLE
                            goodsStandardCollocateTT.run {
                                text = "配置"
                                visibility = View.VISIBLE
                            }
                            attrAdapter.run {
                                setPosition(-1)
                                notifyDataSetChanged()
                                data.clear()
                                data.addAll(productSpecs.配置)
                                notifyDataSetChanged()

                                setOnItemClickListener { _, _, position ->
                                    attrSelect.text = "${data[position]}"
                                    selectedOptions["配置"] = when(position) {
                                        1 -> 100
                                        2 -> 200
                                        3 -> 300
                                        4 -> 400
                                        else -> 0
                                    }
                                    setPosition(position)
                                    notifyDataSetChanged()
                                    updateTotalPrice()
                                }
                            }
                            goodsStandardCollocateRV.run {
                                adapter = attrAdapter
                                layoutManager = LinearLayoutManager(this@GoodsDetailActivity, LinearLayoutManager.HORIZONTAL, false)
                            }
                        }
                        // 颜色规格
                        if (goodsEntityItem.goods_attribute.contains("颜色")) {
                            colorSelect.visibility = View.VISIBLE
                            goodsStandardColorTT.run {
                                text = "颜色"
                                visibility = View.VISIBLE
                            }

                            colorAdapter.run {
                                setPosition(-1)
                                notifyDataSetChanged()
                                data.clear()
                                data.addAll(productSpecs.颜色)
                                notifyDataSetChanged()
                                setOnItemClickListener { _, _, position ->
                                    colorSelect.text =data[position]
                                    selectedOptions["颜色"] = when(position) {
                                        1 -> 100
                                        2 -> 200
                                        3 -> 300
                                        4 -> 400
                                        else -> 0
                                    }
                                    setPosition(position)
                                    notifyDataSetChanged()
                                    updateTotalPrice()
                                }
                            }
                            goodsStandardColorRV.run {
                                adapter = colorAdapter
                                layoutManager = LinearLayoutManager(this@GoodsDetailActivity, LinearLayoutManager.HORIZONTAL, false)
                            }
                        }
                    }

                    override fun onDismiss() {
                        super.onDismiss()

                    }
                })
            popup.show()
        }
        //评论
        binding.goodsDetailCommentRv.adapter = commentAdapter
        binding.goodsDetailCommentRv.layoutManager = LinearLayoutManager(this)
        commentAdapter.data.add(CommentEntity("大家急急急","电脑非常好，质量太棒了！",R.drawable.sunrise))
        commentAdapter.data.add(CommentEntity("手动阀手动阀","电脑非常好！",R.drawable.a))
        commentAdapter.data.add(CommentEntity("sddfdf","电脑非常好撒旦发射点发射点发射点手动阀手动阀",R.drawable.boy))

        binding.goodsDetailCommentNum.setOnClickListener {
            ARouter.getInstance().build(RoutePath.GOODS_COMMENT).navigation()
        }
        //客服
        binding.itemGoodsDetailKf.setOnClickListener {
            ARouter.getInstance().build(RoutePath.GOODS_WEBVIEW).withSerializable("kf",goodsEntityItem).navigation()
        }
    }

    override fun initData() {

    }

}